#include "portablecollector.h"
#include "ui_portablecollector.h"
#include "jlog.h"
#include <QDebug>
#include <QNetworkInterface>

int CollectType = 1;  // 1:连续采集;2:触发采集
int Frequency = 1000;
int TimeLength = 5;
int VoltageLevel = 10;
bool IsCollect = false;
int KeyBoardType = 0; // 1: TimeLength; 2: VoltageLevel
QString CurrentPath;
QVector<QString> DataDates; // 保存数据时间，方便操作文件
extern QVector<int> ZeroValue;
extern QVector<int> FullValue;
int TriggerMode = 1; // 1:内时钟启动采集, 13:外触发信号高电平启动采集
QMutex MuteParse;
QMutex MuteDisp;   // 显示线程锁
QMutex MuteSave;

PortableCollector::PortableCollector(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PortableCollector)
{
    ui->setupUi(this);

    Init();
}

PortableCollector::~PortableCollector()
{
    delete ui;

    if(SockCmd->isOpen())
        SockCmd->abort();
    delete SockCmd;
    if(SockData->isOpen())
        SockData->abort();
    delete SockData;
    if(DKeyBoard) {
        delete DKeyBoard;
        DKeyBoard = NULL;
    }
    delete RcvThread;
    JRcv.quit();
    JRcv.wait();
    delete BufThread;
    JBuf.quit();
    JBuf.wait();
    delete ParseThread;
    JParse.quit();
    JParse.wait();
    delete SaveThread;
    JSave.quit();
    JSave.wait();
    delete Display;
    JDisp.quit();
    JDisp.wait();
}


//************************函数*************************************
bool PortableCollector::Init()
{
    JLog log;
    log.WriteLog("start.");
    qRegisterMetaType<DateTimeInfo>("DateTimeInfo");
    // 无边框
    setWindowFlags(Qt::FramelessWindowHint);
    // 挂载SD卡
//    QProcess::execute("mount -t vfat /dev/mmcblk0 /mnt");

    IsSDCardCheck = false;
    IsSDCardEnable = true;
    // 初始化控件
    InitCtrls();
    // 加载控件历史数据
//    InitCtrlsData();

    EnableChannelInfo(false);
    ui->label_TipInfo->setVisible(false);
    HideTipInfoTimer = new QTimer(this);
    connect(HideTipInfoTimer, SIGNAL(timeout()), this, SLOT(HideTipInfo()));

    ReadConfigFile();

    DKeyBoard = new DigitKeyBoard(this);
    DKeyBoard->hide();
    connect(DKeyBoard, SIGNAL(SendKeyWord(char)), this, SLOT(ReceiveKeyWord(char)));

//    CurrentPath = QCoreApplication::applicationDirPath(); // 程序运行目录
    CurrentPath = "/mnt"; // SD卡挂载目录

    InitNetwork();
    InitThreads();

    log.WriteLog("Finshed init.");
    return true;
}

bool PortableCollector::InitCtrls()
{
    // 初始化左侧操作界面
    ui->widget_interaction->setGeometry(0, 0, this->width() * WIDTHRATIO, this->height());
    QPoint BtnColl = ui->pushBtn_Coll->pos();
    ui->pushBtn_Coll->setGeometry((ui->widget_interaction->width() - ui->pushBtn_Coll->width()) / 2, BtnColl.y(),
                                  ui->pushBtn_Coll->width(), ui->pushBtn_Coll->height());
    //
    ui->pushBtn_SubVoltage->setVisible(false);
    ui->pushBtn_AddVoltage->setGeometry(ui->pushBtn_AddVoltage->x(), ui->pushBtn_AddVoltage->y(),
                                        32, ui->pushBtn_AddVoltage->height());
    ui->pushBtn_SubTime->setVisible(false);
    ui->pushBtn_AddTime->setGeometry(ui->pushBtn_AddTime->x(), ui->pushBtn_AddTime->y(),
                                     32, ui->pushBtn_AddTime->height());
    // 默认选择连续采集方式
    ui->radioBtn_SDCard->setAutoExclusive(false);
    ui->radioBtn_Sync->setAutoExclusive(false);
    ui->radioBtn_SeriesColl->setChecked(true);
    // 频率下拉框
    ui->comboBox_Freq->addItems(QStringList() << "500" << "1000" <<
                                "2000" << "4000" << "8000" <<
                                "16000" << "32000");
    ui->comboBox_Freq->setCurrentIndex(1);
    // 初始化提示信息Label不显示

    // 分隔线
    ui->line_Separate->setGeometry(ui->widget_interaction->width(), 0,
                                   ui->line_Separate->width(), ui->line_Separate->height());

    // 初始化右侧波形展示界面
    ui->widget_wave->setGeometry(ui->widget_interaction->width(), 0,
                                 this->width() - ui->widget_interaction->width(), this->height());
    // Layout充满窗口
    ui->widget_wave->setLayout(ui->hLayout_Wave);
    for(int i = 0; i < 250; i++)
        xValue.push_back(i);
    // 波形控件初始化
    WaveChannels.clear();
    for(int i = 0; i < CHANNELCOUNT; i++) {
        QCustomPlot *qcp = new QCustomPlot(this);
        qcp->yAxis->setRange(0, 250);
        qcp->yAxis->setRange(-1000, 1000);
        qcp->xAxis->setVisible(false);
        WaveChannels.push_back(qcp);
        WaveChannels.at(i)->addGraph();
        WaveChannels.at(i)->graph(0)->setPen(QPen(Qt::blue));
        if(i < CHANNELCOUNT / 2)
            ui->vLayout_LeftWava->addWidget(WaveChannels.at(i));
        else
            ui->vLayout_RightWave->addWidget(WaveChannels.at(i));
    }
    JLog log;
    log.WriteLog("Finished init ctrls.");

    return true;
}

void PortableCollector::InitCtrlsData()
{
    QString str;
    // 加载控件历史数据
    QSettings cf("/home/default/Collector/Config.cfg", QSettings::IniFormat);
    // 连续采集
    str = cf.value("/CtrlsCfg/SerColl").toString();
    if(str == "1")
        on_radioBtn_SeriesColl_clicked();
    // 触发采集
    str = cf.value("/CtrlsCfg/TrigColl").toString();
    if(str == "1")
        on_radioBtn_TrigColl_clicked();
    // 同步采集
    str = cf.value("/CtrlsCfg/SyncColl").toString();
    if(str == "1")
        on_radioBtn_Sync_clicked();
    // 采样频率
    str = cf.value("/CtrlsCfg/Frequency").toString();
    if(!str.isEmpty())
        ui->comboBox_Freq->setEditText(str);
    // 存储时长
    str = cf.value("/CtrlsCfg/TimeLen").toString();
    if(!str.isEmpty())
        ui->lineEdit_Time->setText(str);
    // 触发电平
    str = cf.value("/CtrlsCfg/VolLevel").toString();
    if(!str.isEmpty())
        ui->lineEdit_Voltage->setText(str);
}

void PortableCollector::InitNetwork()
{
    SockCmd = new QTcpSocket(this);
    QSettings cf("/home/default/Collector/Config.cfg", QSettings::IniFormat);
    QString Ip = cf.value("/Network/IP").toString();
    SockCmd->abort();
    if(Ip.isEmpty())
        SockCmd->connectToHost(QNetworkInterface::allAddresses().at(2).toString(), 8000);
    else
        SockCmd->connectToHost(Ip, 8000);
    connect(SockCmd, SIGNAL(readyRead()), this, SLOT(CmdSockMessage()));
    connect(SockCmd, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(CmdSockError(QAbstractSocket::SocketError)));

    SockData = new QTcpSocket(this);
    QSettings Rcf("/home/default/Collector/Config.cfg", QSettings::IniFormat);
    Ip = Rcf.value("/Network/IP").toString();
    SockData->abort();
    if(Ip.isEmpty())
        SockData->connectToHost(QNetworkInterface::allAddresses().at(2).toString(), 8001);
    else
        SockData->connectToHost(Ip, 8001);

    cmdArray[0] = {0x0A, 0x10, 1};  //设置AD采集范围
    cmdArray[1] = {0x0E, 0x10, 1};  //设置模拟量通道进入FIFO
    cmdArray[2] = {0x0F, 0x10, 1};  //设置AD采集输入源类型
    cmdArray[3] = {0x10, 0x10, 1};  //设置AD采集频率
    cmdArray[4] = {0x14, 0x10, 1};  //设置AD每次传输数据字节数
    cmdArray[5] = {0x16, 0x10, 1};  //启动或停止AD采集
    cmdArray[6] = {0x17, 0x10, 1};  //设置主动传输数据
    cmdArray[7] = {0x23, 0x10, 1};  //设置计数器IO1~IO16是否进入FIFO
    cmdArray[8] = {0x35, 0x10, 1};  //设置计数器CT1~CT4是否进入FIFO
    cmdArray[9] = {0xC2, 0x10, 1};   //设置编码器EC1~EC4是否进入FIFO
}

void PortableCollector::InitThreads()
{
    RcvThread = new RcvData(SockData);
    RcvThread->moveToThread(&JRcv);
    connect(&JRcv, SIGNAL(finished()), &JRcv, SLOT(deleteLater()));
    connect(&JRcv, SIGNAL(finished()), RcvThread, SLOT(deleteLater()));
    connect(RcvThread, SIGNAL(ConnectError()), this, SLOT(RcvDataConnectErr()));
    BufThread = new DataBufThread;
    BufThread->moveToThread(&JBuf);
    connect(&JBuf, SIGNAL(finished()), &JBuf, SLOT(deleteLater()));
    connect(&JBuf, SIGNAL(finished()), BufThread, SLOT(deleteLater()));
    connect(RcvThread, SIGNAL(SendData(QByteArray)),
            BufThread, SLOT(RcvDataSlot(QByteArray)));
    ParseThread = new ParseDataThread;
    ParseThread->moveToThread(&JParse);
    connect(&JParse, SIGNAL(finished()), &JParse, SLOT(deleteLater()));
    connect(&JParse, SIGNAL(finished()), ParseThread, SLOT(deleteLater()));
    connect(BufThread, SIGNAL(SendData(QByteArray)),
            ParseThread, SLOT(ReceiveData(QByteArray)));
    // 触发采集保存数据提醒
    connect(ParseThread, SIGNAL(TrigDataTip()), this, SLOT(TrigDataTip()));
    connect(ParseThread, SIGNAL(SendNoiseValue(float*)),
            this, SLOT(DisplayNoiseValue(float*)));
    SaveThread = new SaveDataThread;
    SaveThread->moveToThread(&JSave);
    connect(&JSave, SIGNAL(finished()), &JSave, SLOT(deleteLater()));
    connect(&JSave, SIGNAL(finished()), SaveThread, SLOT(deleteLater()));
    // 保存数据槽函数
    connect(ParseThread, SIGNAL(SendData(DateTimeInfo,QVector<float>*)),
            SaveThread, SLOT(ReceviceData(DateTimeInfo,QVector<float>*)));
    // 保存数据失败提醒
    connect(SaveThread, SIGNAL(SaveDataError()), this, SLOT(SaveDataError()));
    // 触发采集保存完提示信息切换
    connect(SaveThread, SIGNAL(FinishedTrigSave()), this, SLOT(FinishedTrigSave()));
    Display = new DisplayThread;
    Display->moveToThread(&JDisp);
    connect(&JDisp, SIGNAL(finished()), &JDisp, SLOT(deleteLater()));
    connect(&JDisp, SIGNAL(finished()), Display, SLOT(deleteLater()));
    connect(ParseThread, SIGNAL(SendDisplayDate(QVector<double>*)),
            Display, SLOT(SampeleWaveCount(QVector<double>*)));
    connect(Display, SIGNAL(SendWaveData(QVector<double>*,float*)),
            this, SLOT(SampeleWave(QVector<double>*,float*)));
    connect(Display, SIGNAL(SendSaveData(DateTimeInfo,QVector<float>*)),
            SaveThread, SLOT(ReceviceData(DateTimeInfo,QVector<float>*)));
    // 触发采集保存数据提醒
    connect(Display, SIGNAL(TrigDataTip()), this, SLOT(TrigDataTip()));
    // 底噪测试按钮槽函数
    connect(this, SIGNAL(NoiseTestCollect()),
            Display, SLOT(NoiseTestSignal()));
    // 底噪测试数据槽函数
    connect(Display, SIGNAL(SendNoistTestData(float*)),
            this, SLOT(DisplayNoiseValue(float*)));
    if(JRcv.isRunning())
        JRcv.wait();
    JRcv.start();
    if(JBuf.isRunning())
        JBuf.wait();
    JBuf.start();
    if(JParse.isRunning())
        JParse.wait();
    JParse.start();
    if(JSave.isRunning())
        JSave.wait();
    JSave.start();
    if(JDisp.isRunning())
        JDisp.wait();
    JDisp.start();
}

void PortableCollector::EnableChannelInfo(bool Flag)
{
    ui->label_Info1->setVisible(Flag);
    ui->label_Info2->setVisible(Flag);
    ui->label_Info3->setVisible(Flag);
    ui->label_Info4->setVisible(Flag);
    ui->label_Info5->setVisible(Flag);
    ui->label_Info6->setVisible(Flag);
    ui->label_Info7->setVisible(Flag);
    ui->label_Info8->setVisible(Flag);
}

void PortableCollector::TipInfo(QString info)
{
    ui->label_TipInfo->setVisible(true);
    ui->label_TipInfo->setText(info);
    HideTipInfoTimer->start(1000);
}

void PortableCollector::ReadConfigFile()
{
    int cnt = 0;
    DataDates.clear();
    QSettings cf("/home/default/Collector/Config.cfg", QSettings::IniFormat);
    cnt = cf.value("/Config/Count").toInt();
    for(int i = 0; i < cnt; i++) {
        QString head = QString("/Config/%1").arg(QString::number(i));
        QString data = cf.value(head).toString();
        if(!data.isEmpty())
            DataDates.push_back(data);
    }
}

unsigned int PortableCollector::BuildCmd(int Id, unsigned int Value, char *Cmdbuf)
{
    log.WriteLog("[CMD] Building cmd.");
    int Addr;
    unsigned char Header[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x10, 0x00, 0x00};
    memcpy(Cmdbuf, Header, 16);
    Cmdbuf[5] = 13 + cmdArray[Id].len * 2;
    Cmdbuf[7] = cmdArray[Id].fun;
    Cmdbuf[8] = (cmdArray[Id].addr>>8) & 0xFF;
    Cmdbuf[9] = cmdArray[Id].addr;
    if (cmdArray[Id].fun == 0x10){
        Cmdbuf[10] = (cmdArray[Id].len>>8) & 0xFF;
        Cmdbuf[11] = cmdArray[Id].len & 0xFF;
        Cmdbuf[12] = cmdArray[Id].len * 2;
        Addr = 13;
        switch(Id){
        case CMD_SET_AD_RANGE_E:
        case CMD_SET_EN_AD_CH_E:
        case CMD_SET_AD_INPUT_TYPE_E:
        case CMD_SET_GROUP_CNT_E:
        case CMD_SET_AUTO_SEND_START_E:
        case CMD_SET_AD_START_STOP_E:
        case CMD_SET_SAMPLE_RATE_E:
        case CMD_SET_IO_IN_FIFO_E:
        case CMD_SET_CT_IN_FIFO_E:
        case CMD_SET_EC_IN_FIFO_E:
            Cmdbuf[Addr] = (Value >> 8) & 0xFF;
            Cmdbuf[Addr + 1] = Value & 0xFF;
            break;
        }
        return 13 + cmdArray[Id].len * 2;
    }
    else if(cmdArray[Id].fun == 0x03){
        Cmdbuf[10] = (Value>>8) & 0xFF;
        Cmdbuf[11] = Value & 0xFF;
        return 12;
    }
    log.WriteLog("[CMD] Finished building cmd.");
}

bool PortableCollector::ReadZeroFullValue()
{
    log.WriteLog("[CMD] Send zero and full values cmd.");
    char Cmdbuf[128] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x01, 0x03, 0x00, 0xC8, 0x00, 0x20};
    unsigned int CmdLen = 12;
    if(SockCmd->write(Cmdbuf, CmdLen) < 0) {
        log.WriteLog("[CMD] Read zero and full values error.");
        qDebug() << "Socket send CMD Error!";
        return false;
    }

    return true;
}

void PortableCollector::Em9108Setting()
{
    log.WriteLog("[CMD] Setting cmd.");
    // stop
    SendCmd(CMD_SET_AD_START_STOP_E, 0);
    SockCmd->waitForReadyRead();
    // 高字节为采集数据的有效长度，当前设置为4字节数据。低字节为通道选择位，
    // 当前设置选择1~8, 8个通道
    SendCmd(CMD_SET_EN_AD_CH_E, (4<<8) | 0xFF);
    SockCmd->waitForReadyRead();
    // 设置所有通道接入均为模拟输入
    SendCmd(CMD_SET_AD_INPUT_TYPE_E, 0);
    SockCmd->waitForReadyRead();
    // 设置采样率32K
    SendCmd(CMD_SET_SAMPLE_RATE_E, 0x24);
    SockCmd->waitForReadyRead();
    // 前面左移的是通道号
    // 设置0通道的采集范围为±10V。
    // 高字节为通道号，低字节为AD量程：
    // 量程值 0:±10V 1:±5V 2:±2V 3:±1V
    SendCmd(CMD_SET_AD_RANGE_E, (0 << 8) | 0);
    SockCmd->waitForReadyRead();
    SendCmd(CMD_SET_AD_RANGE_E, (1 << 8) | 0);
    SockCmd->waitForReadyRead();
    SendCmd(CMD_SET_AD_RANGE_E, (2 << 8) | 0);
    SockCmd->waitForReadyRead();
    SendCmd(CMD_SET_AD_RANGE_E, (3 << 8) | 0);
    SockCmd->waitForReadyRead();
    SendCmd(CMD_SET_AD_RANGE_E, (4 << 8) | 0);
    SockCmd->waitForReadyRead();
    SendCmd(CMD_SET_AD_RANGE_E, (5 << 8) | 0);
    SockCmd->waitForReadyRead();
    SendCmd(CMD_SET_AD_RANGE_E, (6 << 8) | 0);
    SockCmd->waitForReadyRead();
    SendCmd(CMD_SET_AD_RANGE_E, (7 << 8) | 0);
    SockCmd->waitForReadyRead();
    ZeroValue.clear();
    FullValue.clear();
    // 读取零点值和满度值
    ReadZeroFullValue();
    SockCmd->waitForReadyRead();
    // 设置IO不进FIFO
    SendCmd(CMD_SET_IO_IN_FIFO_E, 0);
    SockCmd->waitForReadyRead();
    // 设置EC不进FIFO
    SendCmd(CMD_SET_EC_IN_FIFO_E, 0);
    SockCmd->waitForReadyRead();
    SendCmd(CMD_SET_CT_IN_FIFO_E, 0);
    SockCmd->waitForReadyRead();
    //设置每次传输的数据量
    SendCmd(CMD_SET_GROUP_CNT_E, 64);
    SockCmd->waitForReadyRead();
    // 启动主动传输
    SendCmd(CMD_SET_AUTO_SEND_START_E, 1);
    SockCmd->waitForReadyRead();
    log.WriteLog("[CMD] Finished setting cmd.");
}

void PortableCollector::Em9108Start()
{
    log.WriteLog("[CMD] Send start collect cmd.");
    // 1: 内时钟启动采集
    // 5: 外触发信号上升沿启动采集
    // 13: 外触发信号高电平启动采集
    // 21: 外触发信号下降沿启动采集
    // 29: 外触发信号低电平启动采集
    QSettings cfg("/home/default/Collector/Config.cfg", QSettings::IniFormat);
    cfg.setValue("/Collect/TrigMode/", QString("%1").arg(TriggerMode));
    SendCmd(CMD_SET_AD_START_STOP_E, TriggerMode);
}

void PortableCollector::Em9108Stop()
{
    log.WriteLog("[CMD] Send stop collect cmd.");
    SendCmd(CMD_SET_AD_START_STOP_E, 0);
    SendCmd(CMD_SET_AUTO_SEND_START_E, 0);
}

bool PortableCollector::SendCmd(int CmdId, unsigned int Value)
{
    unsigned int CmdLen;
    char Cmdbuf[128];

    CmdLen = BuildCmd(CmdId, Value, Cmdbuf);
    if(SockCmd->write(Cmdbuf, CmdLen) < 0) {
        qDebug() << "Socket send CMD Error!";
        return false;
    }

    return true;
}


//************************事件*************************************
// 开始/停止按钮
void PortableCollector::on_pushBtn_Coll_clicked()
{
    JLog log;
    if(!IsCollect) {
        if(IsSDCardCheck) {
            if(IsSDCardEnable) {
                // start transfer
                QProcess::execute("mount -t vfat /dev/mmcblk0 /mnt");
//                QProcess::execute("mount -t vfat /dev/mmcblk0p1 /mnt");
                IsSDCardEnable = false;
                ui->radioBtn_SDCard->setEnabled(false);
                TipInfo(QString::fromUtf8("start transfer..."));
                ui->pushBtn_Coll->setText(QString::fromUtf8("停止"));
            }
            else {
                // stop transfer
                QProcess::execute("umount /mnt/");
                IsSDCardEnable = true;
                ui->radioBtn_SDCard->setEnabled(true);
                TipInfo(QString::fromUtf8("stop transfer..."));
                ui->pushBtn_Coll->setText(QString::fromUtf8("传输"));
            }
        }
        else {
            // start collect
            QProcess::execute("mount -t vfat /dev/mmcblk0 /mnt");
            log.WriteLog("[Button] start collecting.");
            IsCollect = true;
            ui->pushBtn_Coll->setText(QString::fromUtf8("停止采集"));
            ui->comboBox_Freq->setEnabled(false);
            EnableChannelInfo(false);
            ui->label_Info1->setVisible(true);
            if(CollectType == 1)
                ui->label_Info1->setText(QString::fromUtf8("连续数据采集中..."));
            else
                ui->label_Info1->setText(QString::fromUtf8("等待触发..."));

            Em9108Setting();
            Em9108Start();
        }
    }
    else {
        log.WriteLog("[Button] stop collecting.");
        IsCollect = false;
        ui->pushBtn_Coll->setText(QString::fromUtf8("开始采集"));
        ui->comboBox_Freq->setEnabled(true);
        ui->label_Info1->setVisible(false);
        QProcess::execute("umount /mnt/");
        Em9108Stop();
    }
}

// 底噪测试按钮
void PortableCollector::on_pushBtn_Test_clicked()
{
    QTime time;
    time.start();
    if(IsCollect) {
        TipInfo(QString::fromUtf8("正在采集，请先停止采集!"));
        return;
    }
    else {
        JLog log;
        log.WriteLog("[Button] noise test singnal.");
        if(ui->radioBtn_Sync->isChecked())
            on_radioBtn_Sync_clicked();
        emit NoiseTestCollect();
        while(time.elapsed() < 10)
            QCoreApplication::processEvents();
        on_pushBtn_Coll_clicked();
    }
}

// 时长+
void PortableCollector::on_pushBtn_AddTime_clicked()
{
    if(IsCollect) {
        TipInfo(QString::fromUtf8("正在采集，请先停止采集!"));
        return;
    }
    else {
        if(TimeLength == 60) {
            TipInfo(QString::fromUtf8("已经到达上限！"));
            return;
        }
        KeyBoardType = 1;
        DKeyBoard->show();
    }
}

// 时长-
void PortableCollector::on_pushBtn_SubTime_clicked()
{
    if(IsCollect) {
        TipInfo(QString::fromUtf8("正在采集，请先停止采集!"));
        return;
    }
    else {
        if(TimeLength == 1) {
            TipInfo(QString::fromUtf8("已经到达下限！"));
            return;
        }
        --TimeLength;
        ui->lineEdit_Time->setText(QString::number(TimeLength));
    }
}

// 电压+
void PortableCollector::on_pushBtn_AddVoltage_clicked()
{
    if(IsCollect) {
        TipInfo(QString::fromUtf8("正在采集，请先停止采集!"));
        return;
    }
    else {
//        VoltageLevel += 10;
//        ui->lineEdit_Voltage->setText(QString::number(VoltageLevel));
        KeyBoardType = 2;
        DKeyBoard->show();
    }
}

// 电压-
void PortableCollector::on_pushBtn_SubVoltage_clicked()
{
    if(IsCollect) {
        TipInfo(QString::fromUtf8("正在采集，请先停止采集!"));
        return;
    }
    else {
        if(VoltageLevel <= 0) {
            TipInfo(QString::fromUtf8("已经达到下限!"));
            return;
        }
        VoltageLevel -= 10;
        ui->lineEdit_Voltage->setText(QString::number(VoltageLevel));
    }
}

// 频率
void PortableCollector::on_comboBox_Freq_currentIndexChanged(const QString &arg1)
{
    JLog log;
    Frequency = arg1.toInt();
    QSettings cf("/home/default/Collector/Config.cfg", QSettings::IniFormat);
    cf.setValue("/CtrlsCfg/Frequency", QString::number(Frequency));
    log.WriteLog("[CBOX] Freq Change: " + arg1);
}

// 连续采集
void PortableCollector::on_radioBtn_SeriesColl_clicked()
{
    if(IsCollect) {
        if(CollectType == 1)
            ui->radioBtn_SeriesColl->setChecked(true);
        if(CollectType == 2)
            ui->radioBtn_TrigColl->setChecked(true);
        TipInfo(QString::fromUtf8("正在采集，请先停止采集!"));
        return;
    }
    else {
        JLog log;
        log.WriteLog("[RadioButton] last collect type.");
        CollectType = 1;
        EnableChannelInfo(false);
        QSettings cf("/home/default/Collector/Config.cfg", QSettings::IniFormat);
        cf.setValue("/CtrlsCfg/SerColl", "1");
        cf.setValue("/CtrlsCfg/TrigColl", "0");
    }
}

// 触发采集
void PortableCollector::on_radioBtn_TrigColl_clicked()
{
    if(IsCollect) {
        if(CollectType == 1)
            ui->radioBtn_SeriesColl->setChecked(true);
        if(CollectType == 2)
            ui->radioBtn_TrigColl->setChecked(true);
        TipInfo(QString::fromUtf8("正在采集，请先停止采集!"));
        return;
    }
    else {
        JLog log;
        log.WriteLog("[RadioButton] Trig collect type.");
        CollectType = 2;
        EnableChannelInfo(false);
        QSettings cf("/home/default/Collector/Config.cfg", QSettings::IniFormat);
        cf.setValue("/CtrlsCfg/SerColl", "0");
        cf.setValue("/CtrlsCfg/TrigColl", "1");
    }
}

// 隐藏提示信息定时器
void PortableCollector::HideTipInfo()
{
    ui->label_TipInfo->setVisible(false);
    if(HideTipInfoTimer->isActive())
        HideTipInfoTimer->stop();
}

// 关闭程序事件
void PortableCollector::closeEvent(QCloseEvent *e)
{
    // 解挂载SD卡,mnt后面必须加'/',否则无法解挂载
//    QProcess::execute("umount /mnt/");
    qDebug() << e;
    log.WriteLog("close.");
}

void PortableCollector::InitRcvDataRight()
{
    ui->pushBtn_Coll->setEnabled(true);
    TipInfo(QString::fromUtf8("初始化成功!"));
}

// 底噪测试槽函数
void PortableCollector::DisplayNoiseValue(float *data)
{
    on_pushBtn_Coll_clicked();
    EnableChannelInfo(true);
    ui->label_Info1->setText(QString::number(data[0]));
    ui->label_Info2->setText(QString::number(data[1]));
    ui->label_Info3->setText(QString::number(data[2]));
    ui->label_Info4->setText(QString::number(data[3]));
    ui->label_Info5->setText(QString::number(data[4]));
    ui->label_Info6->setText(QString::number(data[5]));
    ui->label_Info7->setText(QString::number(data[6]));
    ui->label_Info8->setText(QString::number(data[7]));
}

void PortableCollector::SampeleWave(QVector<double> *data, float *MaxValue)
{
//    qDebug() << "disp start: " << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
    QMutexLocker loker(&MuteDisp);
    for(int i = 0; i < CHANNELCOUNT; i++) {
        WaveChannels.at(i)->xAxis->setRange(0, 250);
        WaveChannels.at(i)->yAxis->setRange(-MaxValue[i], MaxValue[i]);
        WaveChannels.at(i)->graph(0)->setData(xValue, data[i]);
        WaveChannels.at(i)->replot();
    }
//    qDebug() << "disp end: " << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
}

// 保存数据失败提醒
void PortableCollector::SaveDataError()
{
    JLog log;
    log.WriteLog("[DATA]save data failed.");
    ui->label_Info1->setText(QString::fromUtf8("保存数据失败！存储空间不足或存储卡损坏!"));
}

// 触发采集保存数据提醒
void PortableCollector::TrigDataTip()
{
    JLog log;
    log.WriteLog("Saving trigger data.");
    ui->label_Info1->setText(QString::fromUtf8("已触发，数据采集保存中..."));
}

void PortableCollector::FinishedTrigSave()
{
    if(IsCollect)
        if(CollectType == 2)
            ui->label_Info1->setText(QString::fromUtf8("等待触发..."));
}

void PortableCollector::ReceiveKeyWord(char Key)
{
    QSettings cf("/home/default/Collector/Config.cfg", QSettings::IniFormat);
    QString Value;
    if(KeyBoardType == 1)
        Value= ui->lineEdit_Time->text();
    else if(KeyBoardType == 2)
        Value= ui->lineEdit_Voltage->text();
    if(Value == "0")
        Value = "";
    switch (Key) {
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
    {
        Value += Key;
        if(KeyBoardType == 1) {
            TimeLength = Value.toInt();
            ui->lineEdit_Time->setText(Value);
        }
        else if (KeyBoardType == 2) {
            VoltageLevel = Value.toInt();
            ui->lineEdit_Voltage->setText(Value);
        }
    }
        break;
    case '.':
        break;
    case 'd':
    {
        Value = Value.left(Value.length() - 1);
        if(Value == "")
            Value = "0";
        if(KeyBoardType == 1) {
            TimeLength = Value.toInt();
            ui->lineEdit_Time->setText(Value);
        }
        else if (KeyBoardType == 2) {
            VoltageLevel = Value.toInt();
            ui->lineEdit_Voltage->setText(Value);
        }
    }
        break;
    case 'c':
    {
        if(KeyBoardType == 1) {
            TimeLength = 0;
            ui->lineEdit_Time->setText("0");
        }
        else if (KeyBoardType == 2) {
            VoltageLevel = 0;
            ui->lineEdit_Voltage->setText("0");
        }
    }
        break;
    default:
        break;
    }
    if(KeyBoardType == 1)
        cf.setValue("/CtrlsCfg/TimeLen", QString::number(TimeLength));
    else if(KeyBoardType == 2)
        cf.setValue("/CtrlsCfg/VolLevel", QString::number(VoltageLevel));
}

void PortableCollector::on_radioBtn_Sync_clicked()
{
    QSettings cf("/home/default/Collector/Config.cfg", QSettings::IniFormat);
    JLog log;
    log.WriteLog("[RadioButton] sync collecting type.");
    if(IsCollect) {
        TipInfo(QString::fromUtf8("正在采集，请先停止采集!"));
        return;
    }
    if(ui->radioBtn_Sync->isChecked()) {
        ui->radioBtn_Sync->setChecked(true);
        if(ui->radioBtn_TrigColl->isChecked()) {
            ui->radioBtn_SeriesColl->setChecked(true);
            ui->radioBtn_TrigColl->setChecked(false);
            CollectType = 1;
        }
        TriggerMode = 0xD;
        CurrentPath = "/mnt/Sync";
        ui->radioBtn_TrigColl->setEnabled(false);
        cf.setValue("/CtrlsCfg/SyncColl", "1");
    }
    else {
        ui->radioBtn_Sync->setChecked(false);
        TriggerMode = 1;
        CurrentPath = "/mnt";
        ui->radioBtn_TrigColl->setEnabled(true);
        cf.setValue("/CtrlsCfg/SyncColl", "0");
    }
    cf.setValue("/CtrlsCfg/SerColl", "1");
    cf.setValue("/CtrlsCfg/TrigColl", "0");
    // resend cmd
}

void PortableCollector::CmdSockMessage()
{
    unsigned int Addr;
    static int cnt = 0;
    QByteArray CmdData = SockCmd->readAll();
    unsigned char *p = (unsigned char*)CmdData.data();
    Addr = (p[8] << 8) + p[9]; // (p[8] << 8)
//    qDebug("%d - Res:%02x, Rst:%02x, Len:%d", cnt, Addr, p[11], CmdData.length());
    if(Addr == 0x4000 || Addr == 0x40FF) {
        for(int i = 9; i < 73; i += 8) {
            ZeroValue.push_back(((p[i + 1] << 16) + (p[i + 2] << 8) + p[i + 3]));
            FullValue.push_back(((p[i + 5] << 16) + (p[i + 6] << 8) + p[i + 7]));
        }
        for(int i = 0; i < ZeroValue.size(); i++) {
            printf("%x, %x\n", ZeroValue[i], FullValue[i]);
            fflush(stdout);
        }
    }

    ++cnt;
}

void PortableCollector::CmdSockError(QAbstractSocket::SocketError err)
{
    qDebug() << "CmdSockError:" << err;
}

void PortableCollector::RcvDataConnectErr()
{
    QTime time;
    time.start();
    log.WriteLog("接收数据线程连接错误，即将重新启动...");
    TipInfo("接收数据线程连接错误，即将重新启动...");
    on_pushBtn_Coll_clicked();
    while(time.elapsed() < 200)
        QCoreApplication::processEvents();
    on_pushBtn_Coll_clicked();
    while(time.elapsed() < 100)
        QCoreApplication::processEvents();
    this->close();
}
#if 1
// tranfer data model
void PortableCollector::on_radioBtn_SDCard_clicked()
{
    if(ui->radioBtn_SDCard->isChecked()) {
        IsSDCardCheck = true;
        ui->radioBtn_SDCard->setChecked(true);
        ui->pushBtn_Coll->setText(QString::fromUtf8("传输"));
    }
    else {
        IsSDCardCheck = false;
        ui->radioBtn_SDCard->setChecked(false);
        ui->pushBtn_Coll->setText(QString::fromUtf8("开始采集"));
    }
}
#endif
